package com.bjsxt.web.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bjsxt.pojo.Funcs;
import com.bjsxt.pojo.Users;

/**
 * Servlet Filter implementation class SafeFilter
 */
public class SafeFilter implements Filter {

    /**
     * Default constructor. 
     */
    public SafeFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		String uri = req.getRequestURI();
		
		HttpSession session = req.getSession();
		if(uri.indexOf("login") != -1 || uri.indexOf("userLogin") != -1){
			chain.doFilter(request, response);
		}else{
			Users user = (Users)session.getAttribute("users");
			List<Funcs> list = user.getFuns();
			boolean flag = false;
			for(Funcs f:list){
				if(uri.indexOf(f.getFuncuri()) != -1){
					flag = true;
					break;
				}
			}
			if(flag){
				chain.doFilter(request, response);
			}else{
				((HttpServletResponse)response).sendRedirect("index.jsp");
			}
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
